rm(list = ls())


# Set Working Directory to Replication Folder
taskdir 		<- "~/Dropbox/final_hai_perlman_replication/"
inputdir 		<- paste0(taskdir, "input/processing/regressions_survey1/")


setwd(taskdir)
library(tidyverse)
library(lfe)
require(data.table)
library(stringi)
library(stargazer)
library(kableExtra)
library(modelsummary)



# Load regression results
load(paste0(inputdir, 'ols_survey1_subset_climatebeleif.RData'))


# We need this only for the main DVs
main_dvs <- c('politician_understand' ,
			  'politician_prevent' ,
			   'politician_advocate' ,
			   'politician_sympathy',
			   'tax_support')
main_dvs_labels <- c('has a good understanding of wildfires and their causes?' ,
			  'will work to prevent future wildfires?' ,
			   'will be an effective advocate for federal disaster relief?' ,
			   'How sympathetic did the politician seem?',
			   'How likely would you be to support this new tax?')


# Collect all models
mods_study <- list()
for (i in 1:length(main_dvs)){
	dv <- main_dvs[i]
	temp_regressions <- outlist[[dv]]
	# extract models for a given dv
	mod1 <- temp_regressions[[1]]
	mod2 <- temp_regressions[[2]]
	mod3 <- temp_regressions[[3]]
	mod4 <- temp_regressions[[4]]


	mods_study[[i]] <- list(
		"(1)" = mod1, 
		"(2)" = mod2, 
		"(3)" = mod3, 
		"(4)" = mod4)
}

for (i in 1:length(main_dvs)) {
	dvlabel <-c(1, 4)
	names(dvlabel) <- c(" ",main_dvs_labels[i])
	# Use model summary to save model summary
	modout<- modelsummary(mods_study[[i]], 
			     output = "latex",
			     vcov = mods_study[[i]]%>%unname()%>%lapply(FUN = function(m)m$rse),
			     stars = c('*' =.1, '**' = .05, '***' = 0.01),
			     notes = 'Regressions also include fixed effects for income level')%>%
	  add_header_above(c(" ", "Pooled" = 1, "Republicans" = 1, "Democrats" = 1, "Independents" = 1))%>%
	  add_header_above(dvlabel)%>%
	  add_header_above(c(" ", "Dependent variable:"=4))
	# output to latex
	save_kable(
		modout,
		file = paste0(taskdir, 'output/regression_tables/ols_survey1_subset_climatebeleif/survey1_table_cc_belief_',i,'.tex'),
	)
	# manually remove \begin and \end table
	flname<- paste0(taskdir, 'output/regression_tables/ols_survey1_subset_climatebeleif/survey1_table_cc_belief_',i,'.tex')
	lines <- readLines(flname) # read file
	lines[1] <- ""           # I wanted to replace the first and last lines
	lines[length(lines)] <- ""
	write(lines,flname)
}




